using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace MeeboClient
{
	/// <summary>
	/// 
	/// </summary>
	public partial class MainForm : Form
	{

		private Window myself = null;
		private Window mBuddyList = null;
		private bool reactOnNewWindow = true;

		public MainForm()
		{
			InitializeComponent();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
			//Registeres the Windowhandler for the Mainform
			myself = new Window("Window Hider", this.Handle, "");

			//Load the Meebo Homepage
			this.webBrowser1.Navigate("http://www.meebo.com");
		}

		private void restartToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//Display the hidden windows
			myself.Visible = true;
			if (this.buddylist != null)
			{
				this.buddylist.Visible = true;
			}
		}

		private void closeToolStripMenuItem_Click(object sender, EventArgs e)
		{
			//close the application
			this.Close();
		}

		private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			//Show the hidden IE Window
			if (this.buddylist != null)
			{
				this.buddylist.Visible = !this.buddylist.Visible;
			}
		}

		private void webBrowser1_NewWindow(object sender, CancelEventArgs e)
		{
			//On undocking of the buddylist -> grab it
			if (reactOnNewWindow)
			{
				Thread grabber = new Thread(new ThreadStart(grabBuddyListThread));
				grabber.Start();
				reactOnNewWindow = false;
			}
		}

		private void grabBuddyListThread()
		{
			Thread.Sleep(15000);

			grabBuddylist();
		}

		private void grabBuddylist()
		{
			//enumerate thru Windows collection
			Windows wndList = new Windows(false, false);
			foreach (Window wnd in wndList)
			{
				//hopefully the name of the buddylist window is in all languages the same
				if (wnd.Title.StartsWith("Buddylist"))
				{
					this.buddylist = wnd;
					break;
				}
			}


			if (this.buddylist != null)
			{
				this.myself.Visible = false;
				this.buddylist.Visible = false;
			}
		}

		public Window buddylist
		{
			get
			{
				return this.mBuddyList;
			}
			set
			{
				this.mBuddyList = value;
			}
		}

		private void grabBuddylistToolStripMenuItem_Click(object sender, EventArgs e)
		{
			grabBuddylist();
		}
	}
}